package com.elysia.blogspringboot.controller.universal;

import com.elysia.blogspringboot.domain.entity.User;
import com.elysia.blogspringboot.properties.JwtProperties;
import com.elysia.blogspringboot.result.Result;
import com.elysia.blogspringboot.service.IUserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/logout")
@RequiredArgsConstructor
@Slf4j
public class LogoutController {
    private final RedisTemplate<String, String> redisTemplate;
    private final JwtProperties jwtProperties;
    @PostMapping
    public Result<String> logout(HttpServletRequest request) {
        log.info("用户退出登录");
        //从Cookie中获取令牌
        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //匹配存储JWT的Cookie名称
                if (jwtProperties.getUserTokenName().equals(cookie.getName())) {
                    token = cookie.getValue();
                    break;
                }
            }
        }
        String key = "user:blacklist:" + token;
        redisTemplate.opsForValue().set(key, token);
        return Result.success();
    }
}
